<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>表单设计</title>
    <link rel="stylesheet" href="../lib/jstree/themes/default/style.css">
    <script src="../lib/jquery/jquery.js"></script>
    <script src="../lib/jstree/jstree.js"></script>
    <script src="../lib/vue/vue-util.js"></script>


    <style>
        html,body,#content{
            width: 100vw;
            height: 100vh;
            overflow: hidden;
            margin: 0 !important;
            padding: 0 !important;
            box-sizing: border-box;
        }
        #content{
            padding: 10px !important;
        }
        .fa-folder-o{
            color: #f90;
        }
        .fa-file-o{
            color: #00a0e8;
        }
    </style>
    <script src="../lib/layer/layer.js"></script>
    <link rel="stylesheet" href="../lib/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <script src="../lib/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="../lib/bootstrap-3.3.7-dist/css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="../lib/font/css/font-awesome.min.css">
</head>
<body>
<div id="content" style="flex-direction: row; display: flex; justify-content: flex-start">
<!--    <div class="alert alert-warning">编辑完成后记得保存</div>-->

    <div style="display: flex; flex-direction: column">

        <div id="jstree_demo" style=" overflow: auto; flex:1">

        </div>

        <div style="text-align: center; padding-bottom: 10px;">
            <a class="btn btn-success btn-sm" href="javascript:;" id="export">导出</a>
            <a class="btn btn-primary btn-sm" href="javascript:;" id="import">导入</a>
        </div>
    </div>
    <div id="dataList" style="flex: 1;margin-left: 10px;margin-right: 10px;">
        <iframe style="display: none;" id="form-edit" src="" width="100%" height="100%" frameborder="0"></iframe>
    </div>
</div>

</body>
</html>
<script>
    function reportMenu(node) {
        // access node as: node.id);
        // build your menu depending on node id
        return {
            createItem: {
                "label": "Create New Branch",
                "action": function(obj) {
                    this.create(obj);
                    alert(obj.text())
                },
                "_class": "class"
            },
            renameItem: {
                "label": "Rename Branch",
                "action": function(obj) { this.rename(obj); }
            },
            deleteItem: {
                "label": "Remove Branch",
                "action": function(obj) { this.remove(obj); }
            }
        };
    }

    // function name2text(items){
    //     $.each(items || [], function (i,v) {
    //         if(!v.text && v.name) {
    //             v.text = v.name;
    //             delete v.name;
    //         }
    //         name2text(v.children);
    //     });
    //     return items
    // }

    var lastClickedNode = null;

    // function onInfront() {
    //     loadFormList(lastClickedNode);
    // }

    // function loadFormList(n){
    //     return;
    //     if(!n){
    //         return
    //     }
    //     loadTimeout();
    //     $.get("/api/bpm/form/list", {pid: n=='top'?undefined:n.node.original.id}, function (data) {
    //         layer.closeAll();
    //         data = data.data;
    //         $("#dataList").empty()
    //         laytableRender({
    //             // url: remoteOrigin + "/api/bpm/form/list",
    //             // currPage: getParam("page") || 1,
    //             data: data||[],
    //             page:false,
    //             cols: [
    //                 [
    //                     // {field:'idex', title:'序号', align:"center" },
    //                     {field:'name', title:'表单名', align:"center" },
    //                     {field:'desc', title:'表单描述', align:"center", width:250 },
    //                     // {field:'createTime', title:'添加时间', align:"center"},
    //                     {field:'lastModify', title:'最后修改时间', align:"center"},
    //                     // {field:'trueName', title:'姓名', width: 150, align:"center" },
    //                     // {field: 'username', title: '用戶名', width: 150, align:"center" },
    //                     // {field:'state', title:'状态',  width: 80, align:"center"},
    //                     // {field:'phone', title:'电话', width: 150, align:"center" },
    //                     {title:'操作', templet: "#toolbar"}
    //                 ]
    //             ],
    //             done: function(res, curr){
    //                 layCurrPage = curr;
    //             }
    //             // onData : function(d){
    //             //     data = d.rows;
    //             //     // console.log(data)
    //             // }
    //         });
    //     },"json");
    //
    //
    // }



    function onFormEdited(type, data){
        if(type == "edit"){
            var node = ins.get_node(data.id);
            if(!node){
                return
            }
            ins.rename_node(node, data.text)
        }
        else{
            var node = ins.get_node(data.pid);
            if(!node){
                return
            }
            ins.create_node(node, data)
            $("#form-edit").hide()
        }
    }

    layer.load(0, {time:5000});
    $.get("/api/bpm/form/listex", {type:"form"},function (msg) {
        layer.closeAll();
        if(!msg.success){
           return
        }
        msg = msg.data;

        // console.log(msg)
        $('#jstree_demo').jstree({
            "core" : {
                "animation" : 0,
                "check_callback" : true,
                "themes" : { "stripes" : true },
                'data' :[
                    {
                        'id' : '',
                        'text' : '全部分类',
                        "type":"home",
                        'state' : { 'opened' : true, 'selected' : true },
                        'children' : (msg)
                    }
                ]
            },
            'contextmenu': {
                'select_node': false,
                'items': function (node) {
                    var menu = {};
                    if(node.type == 'cat' || node.type == 'home'){
                        menu.createCat = {
                            "label": "添加分类",
                            "action": function(obj){
                                // if(node.parents.length >= 2){
                                //     layer.msg("最多只支持1级分类");
                                //     return;
                                // }
                                layer.load(0, {time: 5000});
                                $.get("/api/bpm/cat/add", {pid: node.original.id || node.original.id,type:"0"}, function (msg) {
                                    layer.closeAll()
                                    if(!msg.success) return;
                                    msg = msg.data;
                                    msg.id = msg._id;
                                    console.log(msg)
                                    ins.create_node(node, msg);
                                    ins.open_node(node);
                                },"json")
                            },
                        }
                    } else {
                    }
                    if(node.type == 'cat'){
                        menu.createForm = {
                            label: "添加表单",
                            action: function () {
                                var frame = $("#form-edit");
                                frame.data("id", "")
                                    .attr("src", "../form/form.add.html?pid=" + node.original.id + "&v=" + Math.random())
                                    .show()
                            }
                        }
                        menu.rename = {
                            "label": "重命名",
                            "action": function(obj) {
                                if(node.id == 'top'){
                                    layer.msg("顶级分类无法编辑");
                                    return;
                                }
                                $("#jstree_demo").jstree().edit(node);
                            }
                        }
                    }
                    if(node.type != 'home'){
                        if(node.type == "form"){
                            menu.copy = {
                                label: "复制",
                                action: function () {
                                    var id = node.id;
                                    console.log(node)
                                    $.get("/api/bpm/form/copy", {id:id}, function (msg) {
                                        if(!msg.success) return;
                                        ins.create_node(ins.get_node(node.parent), msg.data)
                                    },"json");
                                }
                            }
                        }
                        menu.delete = {
                            "label": "删除",
                            "action": function() {
                                if(node.id == 'top'){
                                    layer.msg("顶级分类无法删除");
                                    return;
                                }
                                if(node.type == 'cat'){
                                    if(node.children.length){
                                        return layer.msg("该分类下还有内容，无法删除")
                                    }
                                    ins.delete_node(node);
                                    $.get("/api/bpm/cat/delete", {id: node.original.id})
                                }
                                if(node.type == "form"){
                                    ins.delete_node(node);
                                    $.get("/api/bpm/form/del", {id: node.original.id})
                                }
                            }
                        }
                    }
                    return menu;

                    return {
                        createItem: {
                            "label": "添加分类",
                            "action": function(obj){
                                // if(node.original.id.type != ""){
                                // }
                                if(node.parents.length >= 2){
                                    layer.msg("最多只支持1级分类");
                                    return;
                                }
                                layer.load(0, {time: 5000});
                                $.get("/api/bpm/cat/add", {pid: node.original.id || node.original.id,type:"0"}, function (msg) {
                                    layer.closeAll()
                                    if(!msg.success) return;
                                    msg = msg.data;
                                    ins.create_node(node, msg);
                                    ins.open_node(node);
                                },"json")

                                // console.log(node)
                                // var ins = $("#jstree_demo").jstree();
                                // ins.show_contextmenu(node)
                                // getFetch("/api/bpm/cat/add", {pid: node.original.id || node.original.id,type:"0"}, function (msg) {
                                //     layer.closeAll()
                                //     console.log(msg);
                                //     ins.create_node(node, msg);
                                //     ins.open_node(node);
                                // });
                            },
                            "_class": "class"
                        },
                        createForm:{
                            "label": "添加表单",
                            action: function () {
                                var ins = $("#jstree_demo").jstree();
                                ins.show_contextmenu(node)
                                addNavTab("bpm-form-add", "添加表单", "/htmlsrc/bpm/form/form.add.html?pid=" + (node.original.id || ""))
                            }
                        },
                        renameItem: {

                        },
                        deleteItem: {
                            "label": "删除",
                            "action": function() {
                                if(node.id == 'top'){
                                    layer.msg("顶级分类无法删除");
                                    return;
                                }
                                layer.load(0, {time: 5000});
                                $.get("/api/bpm/cat/delete", {id: node.original.id}, function (msg) {
                                    layer.closeAll();
                                    $("#jstree_demo").jstree().delete_node(node)
                                });

                                    // if(node.children && node.children.length > 0){
                                //     layer.msg("无法删除一个非空分类");
                                //     return
                                // }
                                // console.log(node)
                                // $("#jstree_demo").jstree().delete_node(node)
                                // this.delete_node(node);
                            }
                        }
                    };
                }
            },
            "types" : {
                    "#":{
                        icon: "fa fa-home",
                        valid_children: ["cat"]
                    },
                    "home":{
                        icon: "fa fa-home",
                        valid_children: ["cat"]
                    },
                    "cat": {
                        icon: "fa fa-folder-o",
                        valid_children:["form", "cat"]
                    },
                    "form": {
                        icon:  "fa fa-file-o",
                        valid_children:[]
                    }
                // "#" : {
                //     "max_children" : 1,
                //     "max_depth" : 4,
                //     "valid_children" : ["root"]
                // },
                // "root" : {
                //     "icon" : "/static/3.3.8/assets/images/tree_icon.png",
                //     "valid_children" : ["default"]
                // },
                // "default" : {
                //     "valid_children" : ["default","file"]
                // },
                // "file" : {
                //     "icon" : "glyphicon glyphicon-file",
                //     "valid_children" : []
                // }
            },
            "plugins" : [
                "contextmenu", "search",
                // "state",
                "dnd",
                "types", "wholerow"
                // "checkbox"
            ]
        });

        window.ins = $('#jstree_demo').jstree();
        // ins.open_all();
        //选中第一个节点
        // loadFormList('top')

        $("#jstree_demo").on("rename_node.jstree", function (e,n) {
            var name = n.text;
            if(n.node.type == 'cat'){
                $.get("/api/bpm/cat/rename", {id: n.node.original.id, name: name});
            }
        }).on("select_node.jstree", function (e,n) {
            var frame = $("#form-edit");
            var did = frame.data("id");
            if(n.node.original.type != 'form'){
                $("#form-edit").hide()
                return
            }
            var id = n.node.original.id;
            if(did == id){
                frame.show()
                return;
            }
            frame.show()
                .data("id", id)
                .attr("src", "../form/form.add.html?id=" + id + "&v=" + Math.random())
        }).on("move_node.jstree", function (e,d) {
            console.log(d);
            $.get("/api/bpm/form/move",{id: d.node.id, pid: d.parent})
            // console.log(arguments)
            // console.log("drag end")
            // opener.bpmData.nodes[nodeId].condition = ins.get_json()[0].children;
        });;
    }, "json");

    // $(document).on("click", ".edit", function () {
    //     var id =  $(this).data("id");
    //     addNavTab(id, "编辑表单", "/htmlsrc/bpm/form/form.add.html?id=" + id)
    // });
    //
    // $(document).on("click", ".del", function () {
    //     if(confirm("确认删除？")){
    //         getFetch($(this).attr("del-href"), function () {
    //             if(window.onInfront){
    //                 window.onInfront();
    //             }
    //         });
    //     }
    // })

    $("#export").click(function () {
        window.open("../com/export.html?type=form", "form-export", "left=100, top=100, width=500, height=400, location=no")
    });

    $("#import").click(function () {
        $("<input type='file'>").change(function (e) {
            // alert(2)
            // console.log(e.target.files)
            var file = e.target.files[0];
            // alert(3)
            var fd = new FormData();
            fd.append("file", file);
            fd.append("type", "form");
            // alert(2)
            $.ajax({
                url: "/api/bpm/form/load",
                type: "POST",
                dataType:"json",
                data: fd,
                processData: false,  // 告诉jQuery不要去处理发送的数据
                contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
                success: function (msg) {
                    if(!msg.success){
                        layer.alert("导入失败，请检查导入文件是否正确")
                        return
                    }
                    layer.alert("共导入分类" + msg.data.cat + "条，表单" + msg.data.form + "条", function () {
                        location.reload()
                    })
                }
            });
            // console.log(file)
        }).appendTo("body").hide().click();//.remove();
    });

</script>